package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WmMaterialConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author 黄晏凯
 */
@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 图片上传
     *
     * @param multipartFile 多部分文件
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (null == multipartFile || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String name = fileName + postfix;
        InputStream inputStream = null;
        String fileId = null;
        try {
            inputStream = multipartFile.getInputStream();
            fileId = fileStorageService.uploadImgFile("", name, inputStream);
            log.info("上传图片到MinIO中，fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }
        //3.保存到数据库中
        WmMaterial wm = new WmMaterial();
        wm.setUserId(WmThreadLocalUtil.getUser().getId());
        wm.setUrl(fileId);
        wm.setType(WmMaterialConstants.PICTURE);
        wm.setIsCollection(WmMaterialConstants.IS_NOT_COLLECTION);
        wm.setCreatedTime(new Date());
        save(wm);
        //4.返回结果
        return ResponseResult.okResult(wm);
    }

    /**
     * 素材列表查询
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 检查参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        // 分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            lqw.eq(WmMaterial::getIsCollection, 1);
        }
        // 添加用户的id
        WmUser user = WmThreadLocalUtil.getUser();
        lqw.eq(WmMaterial::getUserId, user.getId());
        // 按照时间进行查询
        lqw.orderByDesc(WmMaterial::getCreatedTime);

        page = page(page, lqw);

        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        // 结果返回
        return result;
    }
}